package is.ru.honn.rumblr.http;

import is.ru.honn.rumblr.domain.RumblrLog;
import is.ru.honn.rumblr.exception.RumblrException;
import is.ru.honn.rumblr.util.RubmlrParser;
import is.ru.honn.rumblr.util.RumblrProperties;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;

public class RumblrHttpReader
{
  protected RumblrProperties properties;

  public RumblrHttpReader()
  {
    try
    {
      this.properties = new RumblrProperties();
    }
    catch (ConfigurationException e)
    {
      throw new RumblrException("Can't read configuration properties", e);
    }
  }

  public RumblrLog read() throws RumblrException
  {
    RumblrLog log;

    try
    {
      HttpClient client = new HttpClient();
      PostMethod post = new PostMethod(properties.getReadPath());

      client.executeMethod(post);

      String response = post.getResponseBodyAsString();
      post.releaseConnection();

      Document doc = DocumentHelper.parseText(response);

      RubmlrParser p = new RubmlrParser();
      log = p.parse(doc);
    }
    catch (Exception e)
    {
      throw new RumblrException(e);
    }

    return log;
  }
}